package com.smart.web.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.smart.dao.Page;
import com.smart.dao.PageRequest;
import com.smart.model.Message;
import com.smart.model.User;
import com.smart.util.JSON;
import com.smart.util.JsonUtil;

@Controller
public class MessageController extends BaseController{
	@RequestMapping(value = "admin/message/list")
	public String listMessage(PageRequest pageRequest, Model model){
		Page<Message> page = messageService.findAll(pageRequest);
		model.addAttribute("page", page);
		return "admin/message/list";
	}
	
	@RequestMapping(value = "admin/message/edit", method=RequestMethod.GET)
	public String preEditMessage(Long id, Model model) {
		if(id!=null){
			Message message = messageService.findOne(id);
			model.addAttribute("obj", message);
		}
		return "admin/message/edit";
	}
	
	@RequestMapping(value = "admin/message/edit", method=RequestMethod.POST)
	public String editMessage(Message form, Model model, RedirectAttributes ra) {
		messageService.save(form);
		model.addAttribute("obj", form);
		setSuccessMsg(ra);
		return "redirect:edit?id=" + form.getId();
	}
	
	@RequestMapping(value = "admin/message/delete", method=RequestMethod.GET)
	public @ResponseBody String deleteMessage(Long id) {
		messageService.delete(id);
		return "OK";
	}

	@RequestMapping(value = "message/add")
	public @ResponseBody String saveMessage(HttpSession session, Message message, Long currentId) {
		User user = (User) session.getAttribute("user");
		Long lastMsgTime = (Long) session.getAttribute("lastMsgTime");
		Long now = new Date().getTime();
		// 发消息最小时间间隔30秒 防止刷屏;
		if(lastMsgTime==null | lastMsgTime <=0 || (now - lastMsgTime) > 30000) {
			message.setUserId(user.getId() + "");
			message.setUserName(user.getName());
			messageService.save(message);
			session.setAttribute("lastMsgTime", new Date().getTime());
			return "OK";
		}
		else {
			return "BAD";
		}
	}
	
	@RequestMapping(value = "getMessages")
	public @ResponseBody String getMessages(Long currentId) {
		List<Message> list = messageService.getMessages(currentId);
		return JsonUtil.bean2json(list);
	}
	

}
